<!--线索池-->
<template>
  <view class="container clues_container">
    <u-sticky offset-top="0">
      <view class="channel_tab">
        <u-tabs :list="tabsTitle" @change="tabschange" :current="activeKey" lineColor="#4A76F7" :inactiveStyle="{color: '#8091A4', fontSize: '28rpx'}" :activeStyle="{ color: '#333333', fontWeight: '500'}">
			<template #right>
				<view class="filter_icon">
				  <tm-icon fontSize="24" name="iconfont icon-shaixuanweixuan" :color="filterVisible ? '#165DFF' : '#999999'" @click="openFilter" ></tm-icon>
				</view>
			</template>	
		</u-tabs>
      </view>
    </u-sticky>

    <view class="channel_list" v-if="channelData.length > 0">
	    <view class="current-clue">
		    <text class="title">当前线索</text>
		    <text class="clue-item">（{{currentSum}}条）</text>
	    </view>
        <view v-for="(item,i) in channelData" class="channel_item" :key="i" @click="handleJumpDetail(item)">
			<view class="sheet-container">
				<view class="channel_item_title">
				    <view class="channel_type">
				        <u-tag v-if="item.status == 1" text="潜在客户" bgColor="#E8FFEA" color="#00B42A" size="mini"></u-tag>
				        <u-tag v-if="item.status == 2" text="待处理" bgColor="#E8F3FF" color="#165DFF" size="mini"></u-tag>
				        <u-tag v-if="item.status == 3" text="转客户" bgColor="#E8FFFB" color="#2ACFCE" size="mini"></u-tag>
				        <u-tag v-if="item.status == 4" text="无效客户" bgColor="#F2F3F5" color="#88929E" size="mini"></u-tag>
				    </view>
				  <view v-if="item.follow_at_text" class="sign_time">
				    <text class="sign_text">跟进时间</text>
				    <text class="sign_time_text">{{item.follow_at_text}}</text>
				  </view>
				</view>
				<view class="channel_item_content">
					<view class="cus_item">
						<view class="cus_item_label">姓名</view>
						<view class="cus_item_value">{{item.contact_name}}</view>
					</view>
				  <view class="cus_item">
				    <view class="cus_item_label">手机号</view>
				    <view class="cus_item_value">{{item.mobile}}</view>
				  </view>
				  <view class="cus_item">
				    <view class="cus_item_label">公司名称</view>
				    <view class="cus_item_value">{{item.company_name}}</view>
				  </view>
				  <view class="cus_item">
				    <view class="cus_item_label">线索来源</view>
				    <view class="cus_item_value">{{item.from == 1 ? '自建线索' : '招商小程序'}}</view>
				  </view>
				  <view class="cus_item">
				    <view class="cus_item_label">备注</view>
				    <view class="cus_item_value text-overflow-hidden">{{item.remark}}</view>
				  </view>
				</view>
			</view>
        </view>
    </view>
	<view v-else class="defalue-height">
		<defaultGraph></defaultGraph>
	</view>

    <view class="cus_footer_btn">
      <tm-button block label="新建线索" round="25" @click="addChannel"></tm-button>
    </view>
    <!--     筛选框 -->
    <view class="my-popup">
		<u-popup :show="filterVisible" @close="close" @open="open" mode="top" :round="10" zIndex="10070">
		  <view class="zs_filter_main">
		    <view class="zs_filter_title">搜索</view>
		    <view class="zs_filter_item" style="padding-bottom: 24px;">
		      <up-input v-model="searchParams.keyword" placeholder="支持姓名/手机号/公司名称" border="none" prefixIcon="search" prefixIconStyle="font-size: 16px;color: #909399" customStyle="background: #F9F9F9;border-radius: 34rpx; padding: 20rpx"></up-input>
		    </view>
		    <view class="zs_filter_title">跟进时间</view>
		    <view class="zs_filter_item filter_range_time">
				<view class="filter-time-btn-container">
					<view :class="{'time-btn': true, 'active': fifterActive == item.val}" v-for="(item, i) in filterTime" :key="i" @click="handleItemChange(item)">{{item.name}}</view>
				</view>
		      <view class="month-container">
				  <view class="filter_range" @click="() => selectTime(1)">
				    <text v-if="searchParams.start_time_name">{{searchParams.start_time_name}}</text>
				    <text v-else style="color:#8091A4;">请选择开始月份</text>
				  </view>
				  <text style="margin: 0 20rpx;">至</text>
				  <view class="filter_range" @click="() => selectTime(2)">
				    <text v-if="searchParams.end_time_name">{{searchParams.end_time_name}}</text>
				    <text v-else style="color:#8091A4;">请选择结束月份</text>
				  </view>
			  </view>
		    </view>
		    <view class="zs_filter_btns">
		      <up-button type="primary" shape="circle" plain text="重置" @click="handleReset"></up-button>
		      <up-button type="primary" shape="circle" text="搜索" @click="handleSearch"></up-button>
		    </view>
		  </view>
		</u-popup>
	</view>
	<u-datetime-picker popupMode="bottom" @confirm="handlePickerTimeConfirm" @cancel="handlePickerTimeCancel" confirmColor="#4A76F7" ref="datetimePicker2Ref" :show="timeVisible" v-model="searchValue" mode="date" :formatter="formatter" ></u-datetime-picker>
  </view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { clueList, clueGroupCount } from '@/api_request/api'
import { onReachBottom, onLoad, onShow } from '@dcloudio/uni-app';
import { each } from 'lodash'
import moment from 'moment'

const timeVisible = ref<boolean>(false)
const channelData = ref<any>([])
const activeKey = ref<number>(0)
const currentSum = ref<number>(0)
const searchValue = ref<number | string>(Date.now())

const tabsTitle = ref([
  {
    name: '全部',
	type: 0,
    badge: {
      value: 0,
    },
  },
  {
    name: '潜在客户',
  	type: 1,
    badge: {
      value: 0,
    },
  },
  {
    name: '待处理',
    type: 2,
    badge: {
      value: 0,
    }
  },
  {
    name: '转客户',
    type: 3,
    badge: {
      value: 0,
    }
  },
  {
    name: '无效客户',
    type: 4,
    badge: {
      value: 0,
    }
  }
])

const filterVisible = ref<boolean>(false)
const searchParams = ref<any>({
  status: '', 
  start_time: '', // 开始时间
  end_time: '', // 结束时间
  keyword: '', // 关键字
  page_num: 1, // 页
  page_size: 10 // 几条
})
const isLoading = ref<boolean>(false)
const fifterActive = ref<number>(0)
const filterTime = ref([
	{
		name:'三天内',
		val: 1,
		checked: false
	},
	{
		name:'本周内',
		val: 2,
		checked: false
	},
	{
		name:'本月内',
		val: 3,
		checked: false
	},
	{
		name:'本季度内',
		val: 4,
		checked: false
	}
])
const formatter = (type, value) => {
	  if (type === 'year') {
	    return `${value}年`;
	  }
	  if (type === 'month') {
	    return `${value}月`;
	  }
	  if (type === 'day') {
	    return `${value}日`;
	  }
	  return value;
	};
onLoad(() => {
	handleResetData()
	initData()
})
const handleResetData = ()=> {
	channelData.value = []
	activeKey.value = 0
	currentSum.value = 0
	searchParams.value = {
		status: '',
		start_time: '', // 开始时间
		start_time_name: '', // 开始时间
		end_time: '', // 结束时间
		end_time_name: '', // 结束时间
		keyword: '', // 关键字
		page_num: 1, // 页
		page_size: 10 // 几条
	}
	getChannelList()
}
const handleItemChange = (item:any)=> {
	fifterActive.value = item.val
	searchParams.value.start_time_name = ''
	searchParams.value.end_time_name = ''
	switch(item.val) {
		case 1:
			searchParams.value.start_time = moment().add(-3, 'd').startOf('day').valueOf()
			searchParams.value.end_time = moment().endOf('day').valueOf()
			break
		case 2:
			searchParams.value.start_time = moment().startOf('week').valueOf()
			searchParams.value.end_time = moment().endOf('isoWeek').valueOf()
			break
		case 3:
			searchParams.value.start_time = moment().startOf('month').valueOf()
			searchParams.value.end_time = moment().endOf('month').valueOf()
			break
		case 4:
			searchParams.value.start_time = moment().startOf('quarter').valueOf()
			searchParams.value.end_time = moment().endOf('quarter').valueOf()
			break
	}
}
const getChannelList = (data?) => {
   isLoading.value = true
  clueList(searchParams.value).then(res => {
	isLoading.value = false
    let clueData = res.data.list.map((item:any) => {
		return {
			...item,
			follow_at_text: item.follow_at ? moment(item.follow_at).format('YYYY-MM-DD') : '',
			created_at_text: item.created_at ? moment(item.created_at).format('YYYY-MM-DD') : '',
		}
	})
	channelData.value = [...channelData.value, ...clueData]
	currentSum.value = res.data.total
  }).catch((e:any) => {
	  isLoading.value = false
	  uni.$showMsg(e.message)
  })
}

const initData = () => {
  clueGroupCount({}).then(res => {
    console.log('jp=======渠道统计',res)
    if(res.code == 200) {
		let sum:number = 0
		res.data.forEach((item:any) => {
			sum+=Number(item.count)
			tabsTitle.value.forEach((ele:any) => {
				if(item.status == ele.type) {
					ele.badge.value = item.count
				}
			})
		})
		tabsTitle.value[0].badge.value = sum
	}else {
		uni.$showMsg(res.message)
	}
  }).catch(err => {
	  uni.$showMsg(err.message)
  })
}

const tabschange = ({index, ...item}) => {
	console.log('=====', index, item);
	searchParams.value.status = item.type == 0 ? '' : item.type
	activeKey.value = index
	searchParams.value.page_num = 1
	channelData.value = []
	getChannelList()
}
const close = () => {
  filterVisible.value = false
}
const handleReset = () => {
  close()
  getChannelList()
}
const handleSearch = () => {
  searchParams.value.page_num = 1
  channelData.value = []
  getChannelList()
  close()
}
//  1: 选择开始时间    2：选择结束时间
const selectTimeType = ref<number>(1)
const selectTime = (type) => {
  timeVisible.value = true
  selectTimeType.value = type
}

const openFilter = () => {
  console.log('jp======打开搜索',)
  filterVisible.value = true
}

const handlePickerTimeCancel = ()=> {
	timeVisible.value = false
}
// 选择时间
const handlePickerTimeConfirm = (val) => {
  console.log('jp=======searchParams',val)
  fifterActive.value = 0
  if(selectTimeType.value === 1) {
    searchParams.value.start_time_name = moment(val.value).format('YYYY-MM-DD')
    searchParams.value.start_time = val.value
  }
  if(selectTimeType.value === 2) {
    searchParams.value.end_time_name = moment(val.value).format('YYYY-MM-DD')
    searchParams.value.end_time = val.value
  }
  timeVisible.value = false
}
// 新建线索
const addChannel = () => {
  uni.navigateTo({url: `/subpkg/add_clues/add_clues`})
}
const handleJumpDetail = (item:any) => {
	uni.navigateTo({
		url: `/subpkg/clues_detail/clues_detail?id=${item.id}`
	})
}
onReachBottom(() => {
    if(isLoading.value) return
	searchParams.value.page_num +=1
    getChannelList()
})
// initData()
</script>

<style lang="scss" scoped>
.clues_container{
  font-size: $cus-font-size-14;
  .channel_tab{
    position: relative;
    padding:0 20rpx;
    background: #fff;
    .filter_icon{
       padding-left: 20rpx;
    }
  }
  
  .defalue-height {
	  height: calc(100vh - 120px);
  }
  
  .channel_list {
	  padding: 0 20rpx;
	  box-sizing: border-box;
	    .current-clue {
		    margin: 40rpx 0 4rpx;
		    display: flex;
		    align-items: flex-end;
		  
		    .title {
			    font-size: 32rpx;
			    font-weight: 500;
			    color: #333333;
		    }
		  
		    .clue-item {
			    font-size: 24rpx;
			    color: #8091A4;
		    }
	    }
		
		.channel_item {
			.sheet-container {
				background: #FFFFFF;
				border-radius: 10rpx;
				margin-top: 20rpx;
				padding: 24rpx 0 40rpx 40rpx;
				box-sizing: border-box;
				
				.channel_item_title {
					margin: 0;
					padding: 0 20rpx 24rpx 0;
					box-sizing: border-box;
					
					.channel_type {
						:deep(.u-tag) {
							border: none;
							border-radius: 6rpx 0rpx 6rpx 0rpx !important;
							padding: 6rpx 10rpx !important;
							box-sizing: border-box;
							
							.u-tag__text {
								font-size: 28rpx;
								font-weight: 700;
							}
						}
					}
				}
				
				.channel_item_content {
					padding-top: 30rpx;
					box-sizing: border-box;
					
					.cus_item {
						padding-bottom: 30rpx;
						padding-top: 0;
						box-sizing: border-box;
						
						&:last-child {
							padding-bottom: 0;
						}
						
						.cus_item_label {
							width: 112rpx;
							margin-right: 110rpx;
						}
						.cus_item_value {
							flex: 1;
						}
						.text-overflow-hidden {
							width: 412rpx;
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
						}
					}
				}
			}
		}
  }


}
.zs_filter_btns{
  :deep(button) {
    width: 144px;
  }
}

.my-popup {
	:deep(.u-transition) {
		top: 44px !important
	}
}

.zs_filter_item {
	flex-direction: column;
	
	.filter-time-btn-container {
		display: flex;
		align-items: center;
		
		.time-btn {
			padding: 0 30rpx;
			height: 68rpx;
			box-sizing: border-box;
			font-size: 28rpx;
			color: #8091A4;
			border-radius: 34rpx;
			background-color:  #F9F9F9;
			margin-right: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			&:last-child {
				margin-right: 0;
			}
			
			&.active {
				background: #E4EBFB;
				color: #165DFF;
			}
		}
	}
	
	.month-container {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
		
		.filter_range {
			width: 300rpx;
			height: 68rpx;
			background: #F9F9F9;
			padding: 0;
			display: flex;
			align-items: center;
			padding-left: 20rpx;
			box-sizing: border-box;
		}
	}
}

</style>